package com.example.retrofitdemo2;

import android.app.Application;
import android.util.Log;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class BaseApplication extends Application {
    private static final String TAG="tag";
    public static WeatherRequest weatherRequest;
    @Override
    public void onCreate() {
        super.onCreate();
        initRetrofit();

    }
    private void initRetrofit(){
        Retrofit retrofit=new Retrofit.Builder()
                //添加主机地址
                .baseUrl("http://apis.juhe.cn")
                //RxJava框架
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                //Gson转换插件
                .addConverterFactory(GsonConverterFactory.create())
                .client(new OkHttpClient.Builder()
                        .callTimeout(5, TimeUnit.SECONDS)
                        .connectTimeout(10,TimeUnit.SECONDS)
                        .readTimeout(5,TimeUnit.SECONDS)
                        .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        String url = request.url().url().toString();

                        if (null != request.body()) {
                            String type = request.body().contentType().type();
                            String param = request.body().toString();
                            Log.d(TAG, "请求参数=" + param);
                            Log.d(TAG, "参数类型=" + type);
                        }
                        Response response = chain.proceed(request);
                        String result = response.body().string();
                        Log.d(TAG, "请求地址=" + url);
                        Log.d(TAG, "response=" + result);
//重构返回response
                        return response.newBuilder()
                                .body(ResponseBody.create(response.body().contentType(), result)).build();

                    }
                })
                .build()).build();
        //实例化接口对象，生成请求接口对象
        weatherRequest=retrofit.create(WeatherRequest.class);
    }
}
